<template>
	<div class='page__good-brand'>
		<header class="page__header">
			<h2 class="page__title">品牌管理</h2>
			<el-button
				size="mini"
				type="primary"
				@click="editItem(null)"
			>新增品牌
			</el-button>
		</header>
		<div class="page__main">
			<div class="operate-bar">
				<div class="bar-main">
					<el-input
						v-model="keyword"
						@keyup.enter.native="getList"
						style="width: 260px"
						size="small"
						placeholder="请输入关键词">
						<i
							slot="suffix"
							class="el-input__icon el-icon-search"
							@click="getList"
						></i>
					</el-input>
				</div>
				<div class="bar-sub">

				</div>
			</div>
			<el-table
				v-loading="loading"
				:data="tableData"
				style="width: 100%">
				<el-table-column
					prop="id"
					label="ID"
					width="100px"
				>
				</el-table-column>
				<el-table-column
					prop="name"
					label="品牌名称"
				>
				</el-table-column>
				<el-table-column
					prop="createTime"
					label="创建时间"
				>
				</el-table-column>
				<el-table-column
					prop="updateTime"
					label="更新时间"
				>
				</el-table-column>
				<el-table-column
					label="操作"
				>
					<template slot-scope="prop">
						<el-button
							type="warning"
							size="mini"
							@click="editItem(prop.row)"
						>
							编辑
						</el-button>
						<el-button
							type="danger"
							size="mini"
							@click="deleteItem(prop.row)"
						>
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				background
				layout="prev, pager, next"
				hide-on-single-page
				:page-size="pagination.size"
				:current-page="pagination.page"
				:total="total"
				@current-change="changePage"
			>
			</el-pagination>
		</div>
		<el-dialog
			:title="title"
			:visible.sync="dialogVisible"
			:append-to-body="true"
			custom-class="dialog__goods-category"
			width="30%"
		>
			<el-form
				ref="form"
				:model="form"
				:rules="rules"
				label-width="80px">
				<el-form-item label="品牌名称" prop="name">
					<el-input
						v-model="form.name"
						@input="changeName"
						@blur="validateName"
						size="small"
						placeholder="请输入品牌名称">
						<i
							v-if="nameLoading"
							slot="suffix"
							class="el-input__icon el-icon-loading"></i>
					</el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
		    <el-button
			    size="mini"
			    @click="dialogVisible = false">
			    取消
		    </el-button>
		    <el-button
			    type="primary"
			    size="mini"
			    :loading="saveLoading"
			    @click="saveItem">
			    确定
		    </el-button>
		  </span>
		</el-dialog>
	</div>
</template>

<script>
  import {PAGE_SIZE} from "../../config/constant";
  import {mapState} from 'vuex'

  export default {
    name: "brand",
    data() {
      return {
        loading: false,
        keyword: '',
        pagination: {
          size: PAGE_SIZE,
          page: 1
        },
        dialogVisible: false,
        activeItem: null,
        form: {
          name: ''
        },
        rules: {
          name: [{required: true, message: '请输入品牌名称'}, {
            validator: (rule, value, callback) => {
              callback(this.nameError)
            }
          }]
        },
        nameError: undefined,
        nameLoading: false,
        saveLoading: false
      }
    },
    computed: {
      ...mapState([
        'brandList'
      ]),
      total() {
        return this.brandList.length
      },
      tableData() {
        let {page, size} = this.pagination
        let brandList = this.brandList
        return brandList.slice((page - 1) * size, page * size)
      },
      title() {
        if (this.activeItem) return '编辑' + this.activeItem.name
        return '新增品牌'
      }
    },
    watch: {
      nameError() {
        this.$refs.form.validateField('name')
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      changeName() {
        this.nameError = undefined
      },
      validateName() {

      },
      changePage(page) {
        this.pagination.page = page
      },
      async getList() {
        this.loading = true
        await this.$store.dispatch('getBrandList', this.keyword)
        this.loading = false
      },
      editItem(row) {
        let name = ''
        if (row) {
          name = row.name
        }
        this.activeItem = row
        this.form.name = name
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate()
        })
      },
      deleteItem(row) {
        this.$confirm(`确认删除 ${row.name} ？`, '删除提示', {
          beforeClose: (action, instance, done) => {
            if (action !== 'confirm') {
              done()
              return false
            }
            this.$axios.get('/brand/delete', {
                params: {
                  id: row.id
                }
              })
              .then(({success, message}) => {
                if (success) {
                  done()
                  this.getList()
                } else {
                  this.$message.error(message)
                }
              })
              .catch(({message}) => {
                this.$message.error(message)
              })

          }
        })
      },
      saveItem() {
        this.$refs.form.validate(valid => {
          if (!valid) return false
          let params = {
            name: this.form.name
          }
          if (this.activeItem) {
            params.id = this.activeItem.id
          }
          this.saveLoading = true
          this.$axios.post('/brand/save', params)
            .then(({success, message}) => {
              if (success) {
                this.dialogVisible = false
                this.$message.success('操作成功')
                this.getList()
              } else {
                this.$message.error(message)
              }
            })
            .catch(({message}) => {
              this.$message.error(message)
            })
            .finally(() => {
              this.saveLoading = false
            })
        })
      }
    }
  }
</script>

<style lang='less'>
	.page-brand {

	}
</style>
